package com.example.everying.framework.websocket.handler;

import com.alibaba.fastjson2.JSONObject;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.model.entity.chat.ChatConversationEntity;
import com.example.everying.service.chat.ChatConversationService;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// TypingStatusHandler.java
@Slf4j
@Component
public class TypingStatusHandler implements MessageHandler {

    private static final Map<String, Long> lastTypingTime = new ConcurrentHashMap<>();


    private  static  ChatConversationService chatConversationService;
    @Autowired
    public void setService(ChatConversationService chatConversationService) {
        TypingStatusHandler.chatConversationService = chatConversationService;
    }

    @Override
    public void handle(Session session, JSONObject message) {
        String conversationId = message.getString("conversationId");
        boolean isTyping = message.getBoolean("isTyping");
        String userId = WebSocketChatService.getUserId(session);

        // 防抖：500ms内不重复处理
        long now = System.currentTimeMillis();
        if (now - lastTypingTime.getOrDefault(userId,  0L) < 500) {
            return;
        }
        lastTypingTime.put(userId,  now);

        // 获取聊天对方ID
        String otherUserId = getOtherUserId(conversationId, userId);
        if (otherUserId == null) {
            log.error("无法获取聊天对象的ID");
            return;
        }
        // 构建状态通知
        JSONObject notification = new JSONObject();
        notification.put("type", "typing");
        notification.put("userId", userId);
        notification.put("isTyping", isTyping);

        // 推送给对方
        WebSocketChatService.sendMessageToUserId(otherUserId, notification.toJSONString());
    }

    private String getOtherUserId(String conversationId, String userId) {
        String otherUserId = null;
        ChatConversationEntity entity = chatConversationService.getById(conversationId);
        if (entity.getUser1Id().equals(userId)) {
            otherUserId = entity.getUser2Id();
        } else {
            otherUserId = entity.getUser1Id();
        }
        return otherUserId;
    }

}
